﻿namespace Core.Helper;

interface

uses
  System,
  System.Collections.Generic,
  System.Linq,
  System.Text,
  NHibernate,
  NHibernate.Cfg,
  NHibernate.Tool.hbm2ddl;
type
  HibernateHelper = public class
  private
    class var     _sessionFactory: ISessionFactory;

    class method SessionFactory(createDatabase: System.Boolean): ISessionFactory;

  public
    class method OpenSession: ISession;

    class method CriaDatabase;
  end;


implementation


class method HibernateHelper.SessionFactory(createDatabase: System.Boolean): ISessionFactory;
begin
  if ((_sessionFactory <> nil)) and ((not createDatabase)) then    
    exit _sessionFactory;

  var config := new Configuration().Configure();
  config.AddAssembly('Core');

  if createDatabase then begin
    var schemaExport := new SchemaExport(config);
    schemaExport.Drop(false, true);
    schemaExport.Create(false, true)
  end;

  _sessionFactory := config.BuildSessionFactory();
  exit _sessionFactory
end;

class method HibernateHelper.OpenSession: ISession;
begin
  exit SessionFactory(false).OpenSession()
end;

class method HibernateHelper.CriaDatabase;
begin
  SessionFactory(true)
end;

end.
